package com.zjun.demo.experimentaldemo.indexbar

import com.zjun.demo.experimentaldemo.indexbar.suspension.ISuspensionInterface
import net.sourceforge.pinyin4j.PinyinHelper
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType
import java.text.Collator
import java.util.Collections
import java.util.Locale


object PinyinUtil {

    /**
     * 获取汉字的第一个字母
     */
    fun getFirstLetter(chinese: String): String {
        val outputFormat = HanyuPinyinOutputFormat()
        outputFormat.caseType = HanyuPinyinCaseType.UPPERCASE
        outputFormat.toneType = HanyuPinyinToneType.WITHOUT_TONE
        val chars = chinese.trim { it <= ' ' }.toCharArray()
        try {
            if (chars.isNotEmpty()) {
                val pinyinArray: Array<String> = PinyinHelper.toHanyuPinyinStringArray(chars[0], outputFormat)
                return pinyinArray[0].first().toString()
            }
            return "#"
        } catch (e: Exception) {
            return "#"
        }
    }

    /**
     * 排序数据
     */
    fun sortByLocale(locale: Locale, entities: List<ISuspensionInterface>) {
        val collator = Collator.getInstance(locale)
        val comparator: Comparator<ISuspensionInterface> = Comparator { o1, o2 ->
            collator.compare(o1.getSuspensionTag(), o2.getSuspensionTag())
        }
        Collections.sort(entities, comparator)
    }

}